import { getSessionStorage } from '@ibizstudio/runtime';
import { FetchEventSourceInit, fetchEventSource } from '@microsoft/fetch-event-source';
import { stringify } from 'qs';
import { getCookie, notNilEmpty } from 'qx-util';
import { mergeDeepRight } from 'ramda';

/**
 * xxx
 *
 * @author chitanda
 * @date 2023-10-24 11:10:01
 * @param {string} url
 * @param {IParams} params
 * @return {*}  {string}
 */
function attachUrlParam(url: string, params: IParams): string {
  const strParams: string = stringify(params);
  if (notNilEmpty(strParams)) {
    if (url.endsWith('?')) {
      url = `${url}${strParams}`;
    } else if (url.indexOf('?') !== -1 && url.endsWith('&')) {
      url = `${url}${strParams}`;
    } else if (url.indexOf('?') !== -1 && !url.endsWith('&')) {
      url = `${url}&${strParams}`;
    } else {
      url = `${url}?${strParams}`;
    }
  }
  return url;
}

/**
 * ai 聊天 sse
 *
 * @author chitanda
 * @date 2023-10-24 11:10:06
 * @export
 * @param {string} url
 * @param {IParams} params
 * @param {FetchEventSourceInit} [options={}]
 * @return {*}  {Promise<any>}
 */
export async function aiChatSse(url: string, params: IParams, options: FetchEventSourceInit = {}): Promise<any> {
  url = attachUrlParam(url, params);
  if (!options.headers) {
    options.headers = {};
  }
  const headers = options.headers!;
  // 补充基本认证信息
  {
    const token = getCookie('ibzuaa-token');
    headers.Authorization = `Bearer ${token}`;
    const orgData = getSessionStorage('activeOrgData');
    let systemId = '';
    if (orgData) {
      if (orgData.systemid) {
        systemId = orgData.systemid;
      }
      if (orgData.orgid) {
        headers.srforgid = orgData.orgid;
      }
    }
    headers.srfsystemid = systemId;
  }
  const config = mergeDeepRight(
    {
      openWhenHidden: true,
      method: 'POST',
    },
    options,
  );
  await fetchEventSource(url, config);
}
